#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define NUM 1024

//作为客户端，就必须要知道服务端的IP，因为它要先向server发起链接的请求
class TcpClient
{
public:
    TcpClient(const std::string &serverip, const uint16_t &serverport)
    : _sock(-1), _serverip(serverip), _serverport(serverport)
    {}
    void initClient()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(2);
        }
        //2.tcp的客户端要不要bind？要的，但是不需要自己去bind。尤其是client port要让os自己绑定
        //3.要不要listen？ 不要，客户端不用listen，服务端才要
        //4.要不要accept？ 不要，客户端是链接别人的
        //5.客户端要发起链接，要链接谁？connect()
    }
    void start()
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());

        if (connect(_sock, (struct sockaddr*)&server, sizeof(server)) != 0)
        {
            std::cerr << "socket connect error" << std::endl;
        }
        else 
        {
            std::string msg;
            while(true)
            {
                std::cout <<"Enter# ";
                std::getline(std::cin, msg);
                write(_sock, msg.c_str(), msg.size());

                char buffer[NUM];
                int n = read(_sock, buffer, sizeof(buffer)-1);
                if (n > 0)
                {
                    buffer[n] = 0;
                    std::cout << "Server回显# " << buffer << std::endl;
                }
                else
                {
                    break;
                }
            }
        }
    }

    ~TcpClient()
    {
        if (_sock >= 0) close(_sock);
    }
private:
    int _sock;
    std::string _serverip;
    uint16_t _serverport;
};

